package org.yzhzc.system.service.sysuser.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;
import org.yzhzc.common.core.constants.HttpConstants;
import org.yzhzc.common.core.domain.LoginUser;
import org.yzhzc.common.core.domain.vo.LoginUserVO;
import org.yzhzc.common.core.enums.ResultCode;
import org.yzhzc.common.core.enums.UserIdentity;
import org.yzhzc.common.security.exception.ServiceException;
import org.yzhzc.common.security.service.TokenService;
import org.yzhzc.system.domain.sysuser.entity.SysUser;
import org.yzhzc.system.domain.sysuser.dto.SysUserSaveDTO;
import org.yzhzc.system.mapper.sysuser.SysUserMapper;
import org.yzhzc.system.service.sysuser.ISysUserService;
import org.yzhzc.common.core.domain.R;
import org.yzhzc.system.utils.BCryptUtils;

import java.util.List;

/**
 * 系统用户服务实现类
 * 处理用户相关的业务逻辑
 */
@Service
@RefreshScope
@Slf4j
public class SysUserServiceImpl implements ISysUserService {

    @Autowired
    private SysUserMapper sysUserMapper; // 用户数据访问层

    @Autowired
    private TokenService tokenService; // 处理 token 的服务

    @Value("${jwt.secret}")
    private String secret; // JWT 密钥

    @Override
    /**
     * 用户登录
     *
     * @param userAccount 用户账号
     * @param password    用户密码
     * @return 登录结果
     */
    public R<String> login(String userAccount, String password) {
        // 通过账号去数据库中查询对应的用户信息
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        SysUser sysUser = sysUserMapper.selectOne(queryWrapper
                .select(SysUser::getUserId, SysUser::getPassword, SysUser::getNickName) // 查询字段
                .eq(SysUser::getUserAccount, userAccount)); // 查询条件

        if (sysUser == null) {
            return R.fail(ResultCode.FAILED_USER_NOT_EXISTS); // 用户不存在
        }
        // 验证密码
        if (BCryptUtils.matchesPassword(password, sysUser.getPassword())) {
            // 创建并返回 token
            return R.ok(tokenService.createToken(sysUser.getUserId(),
                    secret, UserIdentity.ADMIN.getValue(), sysUser.getNickName(), null));
        }

        return R.fail(ResultCode.FAILED_LOGIN); // 登录失败
    }

    @Override
    /**
     * 用户登出
     *
     * @param token JWT token
     * @return 是否成功
     */
    public boolean logout(String token) {
        if (StrUtil.isNotEmpty(token) && token.startsWith(HttpConstants.PREFIX)) {
            token = token.replaceFirst(HttpConstants.PREFIX, StrUtil.EMPTY); // 去掉前缀
        }
        return tokenService.deleteLoginUser(token, secret); // 删除用户 token
    }

    @Override
    /**
     * 获取用户信息
     *
     * @param token JWT token
     * @return 用户信息
     */
    public R<LoginUserVO> info(String token) {
        if (StrUtil.isNotEmpty(token) && token.startsWith(HttpConstants.PREFIX)) {
            token = token.replaceFirst(HttpConstants.PREFIX, StrUtil.EMPTY); // 去掉前缀
        }
        LoginUser loginUser = tokenService.getLoginUser(token, secret); // 获取登录用户信息
        if (loginUser == null) {
            return R.fail(); // 登录用户不存在
        }
        LoginUserVO loginUserVO = new LoginUserVO();
        loginUserVO.setNickName(loginUser.getNickName()); // 设置用户昵称
        loginUserVO.setHeadImage(loginUser.getHeadImage());
        return R.ok(loginUserVO); // 返回用户信息
    }

    @Override
    /**
     * 添加新用户
     *
     * @param sysUserSaveDTO 新用户信息
     * @return 添加结果
     */
    public int add(SysUserSaveDTO sysUserSaveDTO) {
        // 检查用户是否已存在
        List<SysUser> sysUserList = sysUserMapper.selectList(new LambdaQueryWrapper<SysUser>()
                .eq(SysUser::getUserAccount, sysUserSaveDTO.getUserAccount()));

        if (CollectionUtil.isNotEmpty(sysUserList)) {
            throw new ServiceException(ResultCode.FAILED_USER_EXISTS); // 用户已存在
        }
        SysUser sysUser = new SysUser();
        sysUser.setUserAccount(sysUserSaveDTO.getUserAccount()); // 设置用户账号
        sysUser.setPassword(BCryptUtils.encryptPassword(sysUserSaveDTO.getPassword())); // 加密密码
        sysUser.setNickName(sysUserSaveDTO.getNickName());
        return sysUserMapper.insert(sysUser); // 添加用户
    }
}
